<template>
	<div class="system-menu-container">
		<el-card shadow="hover">
			<div class="btnStyle">
				<el-button type="primary" icon="ele-Refresh" @click="loadMenuList">刷新</el-button>
				<el-button type="primary" icon="ele-Plus" @click="onOpenAddMenu">新增</el-button>
			</div>
			<el-table :data="state.dataList" stripe style="width: 100%" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
				<el-table-column label="资源名称" show-overflow-tooltip>
					<template #default="scope">
						<SvgIcon :name="scope.row.icon" />
						<span class="ml10">{{ $t(scope.row.name) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="url" label="路由路径" show-overflow-tooltip></el-table-column>
				<el-table-column prop="terminal" width="100" column-key="1123" :show-overflow-tooltip="true" label="适用终端" :formatter="formatTerminal"/>
				<el-table-column prop="sysResource" width="100" column-key="1008" :show-overflow-tooltip="true" label="系统内资源" :formatter="formatTerminal"/>
				<el-table-column prop="perms" header-align="center" align="center" :show-overflow-tooltip="true" label="授权标识"/>
				<el-table-column prop="orderNum" label="排序" show-overflow-tooltip></el-table-column>
				<el-table-column prop="type" header-align="center" align="center" column-key="1003" width="80" label="类型" :formatter="formatTerminal">
				</el-table-column>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
						<el-button type="primary" link @click="onOpenEditMenu(scope.row)">修改</el-button>
						<el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
			<el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="上级资源" prop="parentId">
							<el-cascader :options="state.dataList"
										:props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
										placeholder="请选择上级资源"
										clearable
										class="w100"
										v-model="state.submitForm.parentId">
										<template #default="{ node, data }">
											<span>{{ data.name }}</span>
											<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
										</template>
							</el-cascader>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="name">
							<el-input v-model="state.submitForm.name" placeholder="请输入资源名称" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="别名" prop="alias">
							<el-input v-model="state.submitForm.alias" placeholder="请输入资源别名" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="资源路径" prop="url">
							<el-input v-model="state.submitForm.url" placeholder="请输入资源路径：/sys/menu" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="授权标识" prop="perms">
							<el-input v-model="state.submitForm.perms" placeholder="多个用逗号分隔, 如: user:list,user:create" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="资源类型" prop="type">
							<DicSelect v-model="state.submitForm.type" placeholder="请选择" dicCode="1003" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="图标" prop="perms">
							<IconSelector placeholder="请输入菜单图标" style="width:100%" v-model="state.submitForm.icon" type="all" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="排序" prop="orderNum">
							<el-input v-model="state.submitForm.orderNum" placeholder="排序" maxlength="4" min="0" max="9999" type="number"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否系统资源" prop="sysResource">
							<DicSelect v-model="state.submitForm.sysResource" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="终端" prop="terminal">
							<DicSelect v-model="state.submitForm.terminal" placeholder="请选择" dicCode="1123" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="重定向" prop="redirect">
							<el-input v-model="state.submitForm.redirect" placeholder="资源为目录时必填" maxlength="100"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否隐藏" prop="isHide">
							<DicSelect v-model="state.submitForm.isHide" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否缓存" prop="isKeepAlive">
							<DicSelect v-model="state.submitForm.isKeepAlive" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否固定" prop="isAffix">
							<DicSelect v-model="state.submitForm.isAffix" placeholder="请选择" dicCode="1008" style="width:100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :span="12">
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="sysMenu">
import { ElLoading, ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { ref, reactive, watch, onMounted, defineAsyncComponent } from 'vue'
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { systemApi } from '/@/api/sys/system-api'
const ruleFormRef = ref<FormInstance>()
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

const state = reactive({
	dataForm: {
		terminal: ''
	},
	istenant: import.meta.env.VITE_IS_TENANT,
	typeList: ['目录', '菜单', '按钮'],
	selectList: [],
	dataList: [],
	dataDictionaryList: {} as any,
	submitForm: {
		id: '',
		parentId: '',
		name: '',
		alias: '',
		url: '',
		perms: '',
		type: '1',
		icon: '',
		orderNum: 0,
		sysResource: '1',
		tenantId: '',
		terminal: '1',
		redirect: '',
		isHide: '0',
		isKeepAlive: '1',
		isAffix: '0'
	},
	submitFormRule: {
		parentId: { required: true, message: '请输入上级菜单', trigger: 'blur' },
		name: { required: true, message: '请输入租户名称', trigger: 'blur' },
		url: { required: true, message: '请输URL', trigger: 'blur' },
		type: { required: true, message: '请选择类型', trigger: 'blur' },
		sysResource: { required: true, message: '请选择是否系统内资源', trigger: 'blur' },
		tenantId: { required: true, message: '请选择租户', trigger: 'blur' },
		terminal: { required: true, message: '请选择终端类型', trigger: 'blur' },
		redirect: { required: false, message: '类型为目录时必须设置重定向', trigger: 'blur' },
		isHide: { required: true, message: '请选择是否隐藏', trigger: 'blur' },
		isKeepAlive: { required: true, message: '请选择是否缓存', trigger: 'blur' },
		isAffix: { required: true, message: '请选择是否固定', trigger: 'blur' }
	},
	addOrUpdateVisible: false
})

const loadMenuList = () => {
	systemApi.getMenuList().then(data => {
		state.dataList = data.data
	})
}
// 页面加载时
onMounted(() => {
	// 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['1008', '1123', '1003'])
	// 列表查询
	loadMenuList()
})

watch(() => state.submitForm.type, (val:string) => {
	if(val === '0') {
		state.submitFormRule.redirect.required = true
	}else{
		state.submitFormRule.redirect.required = false
	}
})

// 打开新增菜单弹窗
const onOpenAddMenu = () => {
	// addMenuRef.value.openDialog();
	state.submitForm = {
		id: '',
		parentId: '',
		name: '',
		alias: '',
		url: '',
		perms: '',
		type: '1',
		icon: '',
		orderNum: 0,
		sysResource: '1',
		tenantId: '',
		terminal: '1',
		redirect: '',
		isHide: '0',
		isKeepAlive: '1',
		isAffix: '0'
	}
	state.addOrUpdateVisible = true
}

// 打开编辑菜单弹窗
const onOpenEditMenu = (row:any) => {
	state.submitForm = {
		id: '',
		parentId: '',
		name: '',
		alias: '',
		url: '',
		perms: '',
		type: '1',
		icon: '',
		orderNum: 0,
		sysResource: '1',
		tenantId: '',
		terminal: '1',
		redirect: '',
		isHide: '0',
		isKeepAlive: '1',
		isAffix: '0'
	}
	state.submitForm = row
	state.addOrUpdateVisible = true
	// ruleFormRef.value.resetFields()
}

const formatTerminal = (row:any, column:any, cellValue:any, index:number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue)
		}
	}
}
// 删除当前行
const onTabelRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除资源, 是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		// 提交数据
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		systemApi.deleteMenuInfo(row.id).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('删除成功');
				// 列表查询
				loadMenuList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error('删除失败')
		}).finally(() => {
			loading.close()
		})
	}).catch(() => {})
}

const dataFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 提交数据
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			if(!state.submitForm.id) {
				// 新增
				systemApi.saveMenuInfo(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadMenuList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			} else{
				systemApi.updateMenuInfo(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadMenuList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			}
		}
	})
}
</script>